package com.wdhcr.yygh.oss.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OssUtils
 * @Description oss 上传文件到oss上的工具类
 **/
@Component
public class OssUtils {

    private static String endpoint;
    //阿里云OSS账号
    private static String accessKeyId;
    //阿里云OSS密钥
    private static String accessKeySecret;
    //阿里云OSS上的存储块图片bucket名字
    private static String bucketName;

    /*
     * ============= 配置上传过期时间、大小等等 =========
     */
    /**
     * 上传截止时间（秒）
     */
    private final static long expireTime = 6000;

    /**
     * 上传文件最小（字节）
     */
    private final static long min = 0;
    /**
     * 上传文件最大（字节）
     */
    private final static long max = 10 * 1024 * 1024;

    /**
     * 上传文件的前缀、可忽略
     */
    private final static String dir = "";

    private static String callbackUrl;


    @Value("${yygh.oss.callbackUrl}")
    public void setCallbackUrl(String callbackUrl) {
        OssUtils.callbackUrl = callbackUrl;
    }

    @Value("${yygh.oss.endpoint}")
    public void setEndpoint(String endpoint) {
        OssUtils.endpoint = endpoint;
    }

    @Value("${yygh.oss.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        OssUtils.accessKeyId = accessKeyId;
    }

    @Value("${yygh.oss.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        OssUtils.accessKeySecret = accessKeySecret;
    }

    @Value("${yygh.oss.bucketName}")
    public void setBucketName(String bucketName) {
        OssUtils.bucketName = bucketName;
    }

    //    /*
//     * 上传地址
//     * */
    private static String host;
    //
//    //阿里云图片文件存储目录
////    private static String homeimagedir = "license/";
//
    private static OSSClient ossClientStatic;

    @PostConstruct
    private static void init() {
        host = "https://" + bucketName + "." + endpoint;
        ossClientStatic = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }







    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String key) {
        if (StringUtils.isEmpty(key)) {
            return "";
        }
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        URL url = ossClientStatic.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }



    public static String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return getUrl(split[split.length - 1]);
        }
        return null;
    }



    public static Map<String, String> getOssPolicy() throws UnsupportedEncodingException {
        // 直传有效截止时间
        long expireEndTime = System.currentTimeMillis() + (expireTime * 1000);
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConditions = new PolicyConditions();
        // 设置可上传文件的大小
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, min, max);
        // 设置上传文件的前缀、可忽略
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        // 生成policy
        String postPolicy = ossClientStatic.generatePostPolicy(expiration, policyConditions);
        byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClientStatic.calculatePostSignature(postPolicy);
        // 封装policy等信息
        Map<String, String> aliOssPolicy = new HashMap<>();
        aliOssPolicy.put("ossAccessKeyId", accessKeyId);
        aliOssPolicy.put("policy", encodedPolicy);
        aliOssPolicy.put("signature", postSignature);
        aliOssPolicy.put("dir", dir);
        aliOssPolicy.put("host", host);
        aliOssPolicy.put("expire", String.valueOf(expireEndTime / 1000));
        aliOssPolicy.put("callback", getCallBackBody());
        return aliOssPolicy;

    }


    public static String getCallBackBody() throws UnsupportedEncodingException {
        Map<String, String> map = new HashMap<>();
        map.put("callbackUrl", callbackUrl);
        map.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        map.put("callbackBodyType", "application/x-www-form-urlencoded");
        String s = JSON.toJSONString(map);
        String base64CallbackBody = BinaryUtil.toBase64String(s.getBytes("utf-8"));
        return base64CallbackBody;
    }

}
